

package com.hazelcast.internal.cluster.impl;

import com.hazelcast.cluster.Address;
import com.hazelcast.internal.cluster.AddressChecker;
import com.hazelcast.logging.ILogger;

import java.util.Set;

import static com.hazelcast.internal.util.AddressUtil.matchAnyInterface;

/**
 * Check if {@link Address} belongs to set of trusted one.
 * <p>
 * When no trusted interfaces were explicitly configured then all messages are deemed
 * as trusted.
 */
public final class AddressCheckerImpl implements AddressChecker {

    private final Set<String> trustedInterfaces;
    private final ILogger logger;

    public AddressCheckerImpl(Set<String> trustedInterfaces, ILogger logger) {
        this.trustedInterfaces = trustedInterfaces;
        this.logger = logger;
    }

    @Override
    public boolean isTrusted(Address address) {
        if (address == null) {
            return false;
        }
        if (trustedInterfaces.isEmpty()) {
            return true;
        }

        String host = address.getHost();
        if (matchAnyInterface(host, trustedInterfaces)) {
            return true;
        } else {
            if (logger.isFineEnabled()) {
                logger.fine("Address %s doesn't match any trusted interface", host);
            }
            return false;
        }
    }
}
